<!-- 必填信息 -->
<template>
  <el-form
    ref="api_POST_TrainningVO"
    v-loading="loading"
    :model="api_POST_TrainningVO"
    label-width="110px"
    size="small"
    :rules="api_POST_TrainningVO_Rules"
    @submit.native.prevent
  >
    <el-row :gutter="20">
      <el-col :span="11" class="form_item">
        <el-form-item label="培训名称" prop="name">
          <el-input v-model.trim="api_POST_TrainningVO.name" maxlength="40" placeholder="请输入培训名称" />
        </el-form-item>
      </el-col>
      <el-col :span="11" :offset="2" class="form_item">
        <el-form-item label="培训类型" prop="trainningTypeId">
          <el-select v-model="api_POST_TrainningVO.trainningTypeId" :disabled="trainId ? true : false" placeholder="请选择培训类型" style="width: 100%;">
            <el-option v-for="item in trainningType" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="11" class="form_item">
        <el-form-item label="培训地址" prop="provinceCode">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.provinceCode" />
          <el-cascader v-model="areaList" :options="cache.district" :props="{ value: 'code', label: 'name' }" style="width: 100%;" @change="handleAreaChange" />
        </el-form-item>
      </el-col>
      <el-col :span="11" :offset="2" class="form_item">
        <el-form-item label="详细地址" prop="address">
          <el-input v-model.trim="api_POST_TrainningVO.address" placeholder="详细地址具体到街道" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="11" class="form_item">
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model.trim="api_POST_TrainningVO.contactPerson" maxlength="20" placeholder="请输入联系人" />
        </el-form-item>
      </el-col>
      <el-col :span="11" :offset="2" class="form_item">
        <el-form-item label="联系电话" prop="contactPhoneNumber">
          <el-input v-model.trim="api_POST_TrainningVO.contactPhoneNumber" maxlength="30" placeholder="请输入联系人电话" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="11" class="form_item">
        <el-form-item label="报名时间" prop="entryStartTime">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.entryStartTime" />
          <el-date-picker
            v-model="entryTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleEntryTime"
          />
        </el-form-item>
      </el-col>
      <el-col :span="11" :offset="2" class="form_item">
        <el-form-item label="培训时间" prop="startTime">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.startTime" />
          <el-date-picker
            v-model="trainningTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleTrainTime"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="11" class="form_item">
        <el-form-item label="报到注册时间" prop="checkInStartTime">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.checkInStartTime" />
          <el-date-picker
            v-model="checkInTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleCheckInTime"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" class="form_item">
        <el-form-item label="二级域名" prop="route">
          <el-input v-model.trim="api_POST_TrainningVO.route" placeholder="请输入">
            <template slot="prepend">{{ prefixRoute }}</template>
            <!-- <template v-if="api_POST_CompetitionDTO.tenantId || user.tenantId" slot="append">_{{ api_POST_CompetitionDTO.tenantId || user.tenantId }}</template> -->
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20" type="flex" justify="space-between">
      <el-col :span="4" class="form_item" style="height:auto">
        <el-form-item label="上传图片" prop="logoUrl" style="height:auto">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.logoUrl" />
          <photo-cropper-dialog
            ref="logoUrlPhotoCropper"
            auto-crop-width="400px"
            auto-crop-height="400px"
            :fixed-number="[400, 400]"
            :enlarge="1"
            @photoCropperSave="logoUrlPhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_TrainningVO.logoUrl }" @click="openPhotoCropper('logoUrl')">
            <img v-if="api_POST_TrainningVO.logoUrl" class="show_img" :src="getStaticFileUrl(api_POST_TrainningVO.logoUrl)" alt="">
            <div v-else>
              <i class="el-icon-plus" />
              <p class="img_text">上传LOGO</p>
            </div>
          </div>
          <div class="img_text_under"><span v-if="api_POST_TrainningVO.logoUrl">上传LOGO</span></div>
        </el-form-item>
      </el-col>
      <el-col :span="4" class="form_item" style="height:auto;margin-left: 50px;">
        <el-form-item label-width="0" prop="coverUrl">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.coverUrl" />
          <photo-cropper-dialog
            ref="coverUrlPhotoCropper"
            auto-crop-width="316px"
            auto-crop-height="208px"
            :fixed-number="[316, 208]"
            :enlarge="1"
            @photoCropperSave="coverUrlPhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_TrainningVO.coverUrl }" style="width:150px" @click="openPhotoCropper('coverUrl')">
            <img v-if="api_POST_TrainningVO.coverUrl" class="show_img" :src="getStaticFileUrl(api_POST_TrainningVO.coverUrl)" alt="">
            <div v-else>
              <i class="el-icon-plus" />
              <p class="img_text" style="left:25px">上传封面图</p>
            </div>
          </div>
          <div class="img_text_under"><span v-if="api_POST_TrainningVO.coverUrl">上传封面图</span></div>
        </el-form-item>
      </el-col>
      <el-col :span="4" class="form_item" style="height:auto">
        <el-form-item label-width="0" prop="backgroundUrl" style="text-align:right">
          <el-input v-show="false" v-model.trim="api_POST_TrainningVO.backgroundUrl" />
          <photo-cropper-dialog
            ref="backgroundUrlPhotoCropper"
            auto-crop-width="310px"
            auto-crop-height="166px"
            :fixed-number="[620, 332]"
            :enlarge="2"
            @photoCropperSave="backgroundUrlPhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_TrainningVO.backgroundUrl }" style="width:150px" @click="openPhotoCropper('backgroundUrl')">
            <img v-if="api_POST_TrainningVO.backgroundUrl" class="show_img" :src="getStaticFileUrl(api_POST_TrainningVO.backgroundUrl)" alt="">
            <div v-else>
              <i class="el-icon-plus" />
              <p class="img_text" style="left:25px">上传背景</p>
            </div>
          </div>
          <div class="img_text_under"><span v-if="api_POST_TrainningVO.backgroundUrl">上传背景</span></div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" class="form_item">
        <el-form-item label="报名须知" prop="entryNoticeUrl">
          <el-tooltip class="item" effect="dark" placement="left">
            <div slot="content">文件类型：pdf, doc, docx</div>
            <el-input v-show="false" v-model.trim="api_POST_TrainningVO.entryNoticeUrl" />
            <upload-file
              ref="entryNoticeUpload"
              :action="action"
              file-type="file"
              format-file=".pdf,.doc,.docx"
              :default-file-url="getStaticFileUrl(api_POST_TrainningVO.entryNoticeUrl)"
              default-file-name="报名须知"
              @uploadSuccess="entryNoticeUploadSuccess"
            />
          </el-tooltip>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top:5px">
      <el-form-item label="" label-width="120px" style="margin-right:12px">
        <!-- <Tinymce id="tinymce" v-model="ruleForm.text" :height="300" /> -->
        <Tinymce v-model="api_POST_TrainningVO.entryNotice" :height="130" />
      </el-form-item>
    </el-row>
  </el-form>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import {
  SiSTKWTrainCreateTrainningInput,
  Api_GET_TrainTrainningTypeQO
} from '@/lib/form/train/swaggerForm';
// import { Api_POST_TrainningVO_Rules } from '@/lib/validate/train';
import { api_POST_TrainTrainning, api_PUT_TrainTrainningId, api_GET_TrainTrainningId, api_GET_TrainTrainningType } from '@/extend/api/trainswaggerApi/app';
import { CopyData, deepCopy } from '@/lib';
import uploadFile from './UploadFile';
import photoCropperDialog from './photoCropperDialog';
import Tinymce from '@/components/Tinymce';
import validator from '@/lib/validate/index.js';
export default {
  components: {
    uploadFile,
    photoCropperDialog,
    Tinymce
  },
  props: {
    gameId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    var validateNotice = (rule, value, callback) => {
      const _this = this;
      console.log(_this.api_POST_TrainningVO.entryNoticeUrl);
      if (!_this.api_POST_TrainningVO.entryNotice && !_this.api_POST_TrainningVO.entryNoticeUrl) {
        callback(new Error('需上传报名须知或填写须知内容'));
      } else {
        callback();
      }
    };
    // if (this.$refs.api_POST_TrainningVO && (this.api_POST_TrainningVO.entryNotice || this.api_POST_TrainningVO.entryNoticeUrl)) {
    return {
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/document`,
      // 二级域名路由前缀
      prefixRoute: '',
      Api_GET_TrainTrainningTypeQO: new Api_GET_TrainTrainningTypeQO(),
      api_POST_TrainningVO: new SiSTKWTrainCreateTrainningInput(),
      api_POST_TrainningVO_old: new SiSTKWTrainCreateTrainningInput(),
      // api_POST_TrainningVO_Rules: new Api_POST_TrainningVO_Rules(),
      loading: false,
      api_POST_CompetitionDTO: {},
      // 地区
      areaList: [],
      // 报名日期
      entryTime: [],
      checkInTime: [],
      trainningTime: [],
      trainningType: [],
      trainId: '',
      api_POST_TrainningVO_Rules: { // 必填项，验证密码格式
        name: [
          validator.required('培训名称不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkNameLen(value, '培训标名称数限制50字以内'));
            },
            trigger: 'blur'
          }
        ],
        address: [validator.required('比赛地址不能为空')],
        trainningTypeId: [validator.required('培训类型不能为空', 'change')],
        provinceCode: [validator.required('地区选择不能为空', 'change')],
        cityCode: [validator.required('地区选择不能为空', 'change')],
        countyCode: [validator.required('地区选择不能为空', 'change')],
        contactPerson: [validator.required('联系人不能为空')],
        contactPhoneNumber: [
          validator.required('联系人电话不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkHPhone(value, '手机号码格式错误'));
            },
            trigger: 'blur'
          }
        ],
        route: [
          validator.required('培训主页地址不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkRoute(value, '赛事主页地址格式错误，格式限制字母、数字、-'));
            },
            trigger: 'blur'
          }
        ],
        startTime: [validator.required('时间不能为空', 'change')],
        endTime: [validator.required('时间不能为空', 'change')],
        entryStartTime: [validator.required('日期不能为空', 'change')],
        entryEndTime: [validator.required('日期不能为空', 'change')],
        checkInStartTime: [validator.required('日期不能为空', 'change')],
        checkInEndTime: [validator.required('日期不能为空', 'change')],
        entryNoticeUrl: [
          {
            required: true,
            validator: validateNotice,
            trigger: 'change' }
        ],
        disclaimerNotice: [validator.required('免责声明不能为空', 'change')],
        regulation: [validator.required('竞赛规程不能为空', 'change')],
        backgroundUrl: [validator.required('请上传', 'change')],
        logoUrl: [validator.required('请上传', 'change')],
        coverUrl: [validator.required('请上传', 'change')]
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      user: state => state.user
    })
  },
  watch: {
    gameId: {
      handler(val) {
        if (val) {
          this.trainId = val;
        }
      }
    }
  },
  created() {
    this.initRules();
    this.getDictByType(['district', 'competitionCertificationLevel']);
    this.getDict();
    this.getTrainTrainningType();
    this.prefixRoute = `${location.origin}/train.html#/home/`;
    this.trainId = this.$route.query.gameId || this.$route.params.id;
    // 编辑
    console.log(this.trainId);
    if (this.trainId) {
      this.getGameInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    init() {
      this.$refs.api_POST_TrainningVO.resetFields();
      this.areaList = [];
      this.entryTime = [];
      this.trainningTime = [];
      this.checkInTime = [];
      this.$refs.entryNoticeUpload.init();
      this.$refs.disclaimerNoticeUpload.init();
      this.$refs.regulationUpload.init();
      this.$refs.backgroundUrlPhotoCropper.init();
      this.$refs.logoUrlPhotoCropper.init();
      this.$refs.coverUrlPhotoCropper.init();
    },
    getTrainTrainningType() {
      api_GET_TrainTrainningType(this.Api_GET_TrainTrainningTypeQO).then(res => {
        this.trainningType = res.items || [];
      }, () => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
        this.timeLoading = false;
      });
    },
    // 初始化验证信息
    initRules() {
      const _this = this;
      this.api_POST_TrainningVO_Rules.startTime.push({
        validator(rule, value, callback) {
          console.log(_this.trainningTime);
          // 培训开始日期不能小于报名开始日期
          const _startTime = _this.trainningTime && _this.trainningTime[0];
          const _endTime = _this.trainningTime && _this.trainningTime[1];
          if (_this.trainningTime.length > 1 && new Date(_startTime) < new Date(_this.api_POST_TrainningVO.entryStartTime)) {
            callback(new Error('培训开始日期不能小于报名开始日期'));
          }
          // 培训结束日期不能小于报名结束日期
          if (_this.trainningTime.length > 1 && new Date(_endTime) < new Date(_this.api_POST_TrainningVO.entryEndTime)) {
            callback(new Error('培训结束日期不能小于报名结束日期'));
          }
          callback();
        },
        trigger: 'change'
      });
      this.api_POST_TrainningVO_Rules.checkInStartTime.push({
        validator(rule, value, callback) {
          console.log(_this.trainningTime);
          // 报到注册日期不能大于培训开始日期
          const _startTime = _this.trainningTime && _this.trainningTime[0];
          // const _endTime = _this.trainningTime && _this.trainningTime[1];
          if (_this.trainningTime.length > 1 && new Date(_startTime) <= new Date(_this.api_POST_TrainningVO.checkInEndTime)) {
            callback(new Error('报到注册日期应该在培训开始日期之前'));
          }

          // 培训结束日期不能小于报名结束日期
          const _entryTimeStartTime = _this.entryTime && _this.entryTime[0];
          // const _entryTimeEndTime = _this.entryTime && _this.entryTime[1];
          if (_this.entryTime.length > 1 && new Date(_entryTimeStartTime) > new Date(_this.api_POST_TrainningVO.checkInStartTime)) {
            callback(new Error('培训结束日期应该在报名开始之后'));
          }
          callback();
        },
        trigger: 'change'
      });
    },
    // 获取培训详情
    getGameInfo() {
      this.loading = true;
      api_GET_TrainTrainningId(this.trainId).then(res => {
        this.api_POST_CompetitionDTO = res || {};
        CopyData(this.api_POST_CompetitionDTO, this.api_POST_TrainningVO);
        this.areaList = [this.api_POST_TrainningVO.provinceCode, this.api_POST_TrainningVO.cityCode, this.api_POST_TrainningVO.countyCode];
        this.entryTime = [this.api_POST_TrainningVO.entryStartTime, this.api_POST_TrainningVO.entryEndTime];
        this.trainningTime = [this.api_POST_TrainningVO.startTime, this.api_POST_TrainningVO.endTime];
        this.checkInTime = [this.api_POST_TrainningVO.checkInStartTime, this.api_POST_TrainningVO.checkInEndTime];
        this.api_POST_TrainningVO_old = deepCopy(this.api_POST_TrainningVO);
        this.loading = false;
      }, () => {
        this.$message({ type: 'error', message: '获取培训详情失败！' });
        this.loading = false;
      });
    },
    validSameData() {
      return new Promise(resolve => {
        if (JSON.stringify(this.api_POST_TrainningVO_old) === JSON.stringify(this.api_POST_TrainningVO)) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    },
    submit() {
      return new Promise((resolve, reject) => {
        console.log(this.api_POST_TrainningVO);
        this.$refs.api_POST_TrainningVO.validate(valid => {
          if (valid) {
            // 编辑
            if (this.trainId) {
              this.editGame().then(res => {
                this.api_POST_TrainningVO_old = deepCopy(this.api_POST_TrainningVO);
                resolve(res);
              }, error => {
                reject(error);
              });
            } else {
              this.newGame().then(res => {
                this.api_POST_TrainningVO_old = deepCopy(this.api_POST_TrainningVO);
                resolve(res);
              }, error => {
                reject(error);
              });
            }
          } else {
            reject(false);
          }
        });
      });
    },
    // 新建培训
    newGame() {
      return new Promise((resolve, reject) => {
        // 设置默认值
        this.api_POST_TrainningVO.typeCode = 'Independent';
        this.api_POST_TrainningVO.statusCode = this.api_POST_TrainningVO.statusCode || 'Scheduled';
        this.api_POST_TrainningVO.approveStatusCode = this.api_POST_TrainningVO.approveStatusCode || 'NotApproved';
        api_POST_TrainTrainning(this.api_POST_TrainningVO).then(res => {
          this.$message({ type: 'success', message: '新增培训成功！' });
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '新增培训失败！' + error.error.message });
        });
      });
    },
    // 编辑培训
    editGame() {
      return new Promise((resolve, reject) => {
        api_PUT_TrainTrainningId(this.trainId, this.api_POST_TrainningVO).then(res => {
          this.$message({ type: 'success', message: '提交成功！' });
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '提交失败！' + error.error.message });
        });
      });
    },
    // 处理地区显示
    handleAreaChange() {
      this.api_POST_TrainningVO.provinceCode = this.areaList && this.areaList[0];
      this.api_POST_TrainningVO.cityCode = this.areaList && this.areaList[1];
      this.api_POST_TrainningVO.countyCode = this.areaList && this.areaList[2];
    },
    // 处理报名时间
    handleEntryTime() {
      this.api_POST_TrainningVO.entryStartTime = this.entryTime && this.entryTime[0];
      this.api_POST_TrainningVO.entryEndTime = this.entryTime && this.entryTime[1];
    },
    // 处理培训时间
    handleTrainTime() {
      this.api_POST_TrainningVO.startTime = this.trainningTime && this.trainningTime[0];
      this.api_POST_TrainningVO.endTime = this.trainningTime && this.trainningTime[1];
    },
    // 处理报到注册时间
    handleCheckInTime() {
      this.api_POST_TrainningVO.checkInStartTime = this.checkInTime && this.checkInTime[0];
      this.api_POST_TrainningVO.checkInEndTime = this.checkInTime && this.checkInTime[1];
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    openPhotoCropper(code) {
      this.$refs[code + 'PhotoCropper'].open(this.api_POST_TrainningVO[code]);
    },
    // 报名须知上传
    entryNoticeUploadSuccess(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'entryNoticeUrl', fileUrl.tempUrl);
    },
    // 免责声明上传
    disclaimerNoticeUploadSuccess(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'disclaimerNotice', fileUrl.tempUrl);
    },
    // 竞赛规程上传
    regulationUploadSuccess(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'regulation', fileUrl.tempUrl);
    },
    // 背景回显
    backgroundUrlPhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'backgroundUrl', fileUrl.tempUrl);
    },
    // logo回显
    logoUrlPhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'logoUrl', fileUrl.tempUrl);
    },
    // 封面图回显
    coverUrlPhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_TrainningVO, 'coverUrl', fileUrl.tempUrl);
    }
  }
};
</script>
<style scoped>
.upload_game_img {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  font-size: 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}
.upload_game_img.border {
  border: 1px dotted #DCDFE6;
}
.upload_game_img:hover {
  border-color: #409eff;
}
.upload_game_img .show_img {
  /* max-width: 100%; */
  max-height: 100%;
  border-radius: 4px;
  vertical-align: top;
}
.upload_game_img .img_text {
  font-size: 12px;
  color: rgba(0,0,0,0.65);
  text-align: center;
  position: absolute;
  top: 60px;
  line-height: 20px;
  width: 98px;
}
.img_text_under{
  font-size: 12px;
  color: rgba(0,0,0,0.65);
  text-align: center;
  /* height: 32px; */
}
</style>
